package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.letv.whatslive.common.utils.Constants;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.AutoTask;
import com.letv.whatslive.model.convert.AutoTaskConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * 设备Collection操作DAO
 * Created by wangjian7 on 2015/7/8.
 */
@Repository
public class AutoTaskDAO extends BaseDAO {
    protected String collectionName = "autoTask";

    private static final Logger logger = LoggerFactory.getLogger(AutoTaskDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 插入自动任务信息
     * @param autoTask
     */
    public long insertAutoTask(AutoTask autoTask){
        try {
            DBObject obj = AutoTaskConvert.castAutoTaskConvertToDBObject(autoTask);
            return this.insert(obj);
        } catch (Exception e) {
            logger.error("mongodb insert data error! "+collectionName, e);
            return -1L;
        }
    }

    /**
     * 更新自动任务信息
     * @param autoTask
     */
    public void updateAutoTask(AutoTask autoTask) {
        DBObject queryCondition = new BasicDBObject();
        Long id = autoTask.getId();
        queryCondition.put("_id", id); // 用来确定要修改的文档
        BasicDBObject setValue = (BasicDBObject) AutoTaskConvert.castAutoTaskConvertToDBObject(autoTask);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject updateValue = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, updateValue, true, false);
    }

    public AutoTask getAutoTaskById(Long id) {
        Map<String, Object> queryParams = Maps.newHashMap();
        queryParams.put("id",id);
        return queryAutoTaskByParams(queryParams);
    }

    public List<AutoTask> getAllNotDoAutoTask() {
        Map<String, Object> queryParams = Maps.newHashMap();
        queryParams.put("result",0);
        queryParams.put("activeTimeGte", System.currentTimeMillis()-5*60*1000);
        DBCursor cur = this.dbCollection.find(getBasicDBObjectByParams(queryParams));
        List<AutoTask> result = Lists.newArrayList();
        while (cur.hasNext()) {
            DBObject dbObject = cur.next();
            AutoTask autoTask = AutoTaskConvert.castDBObjectToAutoTask(dbObject);
            result.add(autoTask);
        }
        return result;
    }

    public List<AutoTask> getAllNotDoAutoTaskById(Long pid) {
        Map<String, Object> queryParams = Maps.newHashMap();
        queryParams.put("pid",pid);
        queryParams.put("result",0);
        DBCursor cur = this.dbCollection.find(getBasicDBObjectByParams(queryParams));
        List<AutoTask> result = Lists.newArrayList();
        while (cur.hasNext()) {
            DBObject dbObject = cur.next();
            AutoTask autoTask = AutoTaskConvert.castDBObjectToAutoTask(dbObject);
            result.add(autoTask);
        }
        return result;
    }

    public AutoTask getAutoTaskByPidAndActionAndReult(Long pid, int action, int result) {
        Map<String, Object> queryParams = Maps.newHashMap();
        queryParams.put("pid",pid);
        queryParams.put("action",action);
        queryParams.put("result", result);
        return queryAutoTaskByParams(queryParams);
    }

    public AutoTask getAutoTaskByPidAndActionAndActiveTime(Long pid, int action, int result, Long activeTime) {
        Map<String, Object> queryParams = Maps.newHashMap();
        queryParams.put("pid",pid);
        queryParams.put("action",action);
        queryParams.put("activeTime", activeTime);
        queryParams.put("result", result);
        return queryAutoTaskByParams(queryParams);
    }

    private AutoTask queryAutoTaskByParams(Map params){
        DBObject dbObject = getBasicDBObjectByParams(params);
        DBObject result = dbCollection.findOne(dbObject);
        if (result == null) {
            return null;
        }
        AutoTask autoTask = AutoTaskConvert.castDBObjectToAutoTask(result);
        return autoTask;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("id")));
            }
            if (params.get("pid") != null) {
                query.put("pid", ObjectUtils.toLong(params.get("pid")));
            }
            if (params.get("action") != null) {
                query.put("action", ObjectUtils.toInteger(params.get("action")));
            }
            if (params.get("result") != null) {
                query.put("result", ObjectUtils.toInteger(params.get("result")));
            }
            if (params.get("activeTime") != null) {
                query.put("activeTime", ObjectUtils.toLong(params.get("activeTime")));
            }
            if (params.get("activeTimeGte") != null) {
                query.put("activeTime", new BasicDBObject("$gte",
                        ObjectUtils.toLong(params.get("activeTimeGte"))));
            }
        }
        return query;
    }


}